<template>
  <div id="addSpacePage">
    <h2 style="margin-bottom: 16px">
      {{ route.query?.spaceId ? '修改空间' : '创建空间' }}
    </h2>

    <a-form
      :model="spaceFrom"
      name="basic"
      autocomplete="off"
      @finish="handleSubmit"
      layout="vertical"
    >
      <a-form-item label="空间名称" name="name">
        <a-input v-model:value="spaceFrom.spaceName" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item
        v-if="! (route.query?.spaceId) || (loginUser.id && loginUser.userRole === 'admin')"
        label="空间级别"
        name="spaceLevel"
      >
        <a-select
          :options="spaceLevelOptions"
          v-model:value="spaceFrom.spaceLevel"
          placeholder="请选择空间级别"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%" :loading="loading">{{
          route.query?.spaceId ? '修改' : '创建'
        }}</a-button>
      </a-form-item>
    </a-form>
    <a-card title="空间级别介绍">
      <a-typography-paragraph>
        *目前仅支持开通普通版，如需升级空间，请联系+qq:3282703798
      </a-typography-paragraph>
      <a-typography-paragraph v-for="item in spaceLevelList" :key="item.value">
        {{ item.text }} : 大小 {{ formatSize(item.maxSize ?? 0) }} 数量{{
          item.maxCount
        }}</a-typography-paragraph
      >
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeMount } from 'vue'
import { message } from 'ant-design-vue'

import { useRouter, useRoute } from 'vue-router'
import {
  listSpaceLevelUsingGet,
  getSpaceByIdUsingGet,
  editSpaceUsingPost,
  addSpaceUsingPost,
  updateSpaceUsingPost,
  getSpaceVoByIdUsingGet,
} from '@/api/spaceController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
const route = useRoute()
const loginUser = useLoginUserStore().loginUser
const spaceLevelOptions = ref<any[]>([])
const spaceLevelList = ref<API.SpaceLevel[]>([])
const spaceFrom = reactive<API.SpaceAddRequest>({})

const router = useRouter()

const loading = ref<boolean>(false)
//获取空间级别
const fetchSpaceLevelOptions = async () => {
  const res = await listSpaceLevelUsingGet()
  if (res.data.data) {
    spaceLevelList.value = res.data.data
    spaceLevelOptions.value.push(
      ...res.data.data.map((item: any) => {
        return {
          label: item.text,
          value: item.value,
        }
      }),
    )
  } else {
    message.error('获取空间级别失败')
  }
}
// 提交表单
const handleSubmit = async () => {
  loading.value = true
  let res
  if (route.query?.spaceId) {
    if (loginUser.id && loginUser.userRole === 'admin') {
      //如果修改并且是管理员
      res = await updateSpaceUsingPost({ ...spaceFrom, id: route.query.spaceId })
      if (res.data.code === 0) {
        message.success('修改成功')
        router.push('/admin/space_manage')
      } else {
        message.error('修改失败' + res.data.message)
      }
    } else {
      res = await editSpaceUsingPost({ ...spaceFrom, id: route.query.spaceId })
      if (res.data.code === 0) {
        message.success('修改成功')
      }else {
        message.error('修改失败' + res.data.message)
      }
    }
  } else {
    res = await addSpaceUsingPost({ ...spaceFrom })
    if (res.data.code === 0 && res.data.data) {
      message.success('创建成功')
      router.push({ path: `/space/${res.data.data}` })
    } else {
      message.error('创建失败，' + res.data.message)
    }
  }
  loading.value = false
}

onBeforeMount(() => {
  if (route.query.spaceId) {
    getSpaceById(route.query.spaceId)
  }
})
onMounted(() => {
  fetchSpaceLevelOptions()
})
const getSpaceById = async (spaceId) => {
  let res
  if (loginUser.userRole === 'admin') {
    res = await getSpaceByIdUsingGet({ id: spaceId })
  } else {
    res = await getSpaceVoByIdUsingGet({ id: spaceId })
  }
  if (res.data.code === 0 && res.data.data) {
    spaceFrom.spaceName = res.data.data.spaceName
    spaceFrom.spaceLevel = res.data.data.spaceLevel
  }
}
//数字转换
const formatSize = (size: number) => {
  return size / 1024 / 1024 + 'MB'
}
</script>

<style scoped>
#addSpacePage {
  width: 80%;
  margin: 0 auto;
}
</style>
